package top.wardyan.wbaseswt.control.wtable;

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import com.jfinal.aop.Aop;
import com.jfinal.plugin.activerecord.IRow;

import top.wardyan.wbaseswt.conf.model.SysTableCol;
import top.wardyan.wbaseswt.conf.service.ISysTableColService;

public class WTableColumn extends TableColumn{
	
	//protected static final SQLite sqlite = SQLite.getInstance();
	//protected static final IYTTableColService tableColService = SQLite.getInstance().tablecolService;
	
	protected WTableColumn self;
	// 排序类型. 0未排序, 1已正序排序, -1已反序排序
	private int sortType = 0;
	
	protected Map<String, String> replace = null;
	protected String format = null;
	/**
	 * 2020-02-13 22:46:52 harrydeep@wardyan.top 指向数据库中的栏位名
	 * NO 因为可能还要搞筛选
	 */
	//private String xField;
	/** 表格名.需要设置表格名才能 **/
	protected String tableName;
	protected String xField;
	protected int type; // 1文本 2数值 3日期 4SELECT下拉
	
	public WTableColumn(Table parent, int style) {
		super(parent, style);
		this.createContent();
	}
	
	public WTableColumn(Table parent, int style, int index) {
		super(parent, style, index);
		this.createContent();
	}
	
	public WTableColumn(Table parent, String text, int width, int align) {
		this(parent, SWT.NONE);
		this.setText(text);
		this.setWidth(width);
		this.setAlignment(align);
	}
	public WTableColumn(Table parent, String text, int width) {
		this(parent, text, width, SWT.LEFT);
	}
	//**
	public WTableColumn(Table parent, int style, String tablename, String xField) {
		super(parent, style);
		this.tableName = tablename;
		this.xField = xField;
		this.createContent();
	}
	public WTableColumn(Table parent, int style, int index, String tablename, String xField) {
		super(parent, style, index);
		this.tableName = tablename;
		this.xField = xField;
		this.createContent();
	}
	
	public WTableColumn(Table parent, int style, String text, int width, int align, String tablename, String xField) {
		this(parent, style, tablename, xField);
		this.setText(text);
		this.setWidth(width);
		this.setAlignment(align);
	}
	public WTableColumn(Table parent, int style, String text, int width, String tablename, String xField) {
		this(parent, style, text, width, SWT.LEFT, tablename, xField);
	}
	public WTableColumn(Table parent, int style, String text, String tablename, String xField) {
		//this(parent, style, text, tablename, xField);
		super(parent, style);
		this.tableName = tablename;
		this.xField = xField;
		this.setText(text);
		this.createContent();
	}
	
	
	private void createContent() {
		self = this;
		this.setMoveable(true);
		// 点击排序
		// 首先决定要什么方法排序
		this.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(sortType == 0) sortType = -1;
				sortType *= -1;
				
				Table tb = self.getParent();
				TableItem[] items = tb.getItems();
				//self.getParent()
				TableColumn[] cols = tb.getColumns();
				int index = 0;
				for(TableColumn c : cols) {
					if(c == self) {
						break;
					}
					index ++;
				}
				//System.out.println(index);
				//String text =
				// 循环检测每一个文本, 确定是数值还是字符串 至于日期的就先不搞
				boolean isNumber = true;
				for(TableItem i : items) {
					String text = i.getText(index);
					try {
						float f = Float.valueOf(text);
					}catch(Exception ex) {
						isNumber = false;
						break;
					}
				}
				final int i = index;
				final boolean _isNumber = isNumber;
				// 如果是数值
				//if(isNumber) {
				final int sort = sortType;
				Arrays.sort(items, new Comparator<TableItem>() {
					@Override
					public int compare(TableItem o1, TableItem o2) {
						
						String s1 = o1.getText(i);
						String s2 = o2.getText(i);
						if(s1 == null) s1 = "";
						if(s2 == null) s2 = "";
						if(_isNumber) {
							return Float.valueOf(s1).compareTo(Float.valueOf(s2)) * sortType;
						}else {
							return s1.compareTo(s2) * sortType;
						}
					}
				});
				//String[][] rs = new String[items.length][cols.length];
				Map<String[], IRow<? extends IRow<?>>> maps = new LinkedHashMap<>();
				index = 0;
				for(TableItem item : items) {
					String[] array = new String[cols.length];
					int n = 0;
					while(n < cols.length) {
						array[n] = item.getText(n);
						n++;
					}
					//rs[index] = array;
					maps.put(array, ((WTableItem)item).getModel());
					index++;
				}
				
				tb.removeAll();
//				for(String[] a : rs) {
//					new WTableItem(tb, SWT.NONE, a);
//				}
				for(String[] a : maps.keySet()) {
					WTableItem ti = new WTableItem(tb, SWT.NONE, a);
					ti.setModel(maps.get(a));
				}
				
			}
		});
		
		try {
			// ISysTableColService tableColService = SQLite.getInstance().tablecolService;
			ISysTableColService tableColService = Aop.get(ISysTableColService.class);			
			// this.setFont(Const.getDefaultFont());
			//this.setAlignment();
			// 所在窗体的名称,包括包名
			// System.out.println(this.getParent().getShell().getClass().getName());
			// table变量名
			//System.out.println(this.getParent());
			if(this.xField != null && this.xField.length() > 0 && this.tableName != null && this.tableName.length() > 0) {
				String name = this.getParent().getShell().getClass().getName();
				SysTableCol c = tableColService.find(name, this.tableName, this.xField);
				if(c != null) {
					this.setText(c.getXTitle() != null ? c.getXTitle() : this.getText());
					this.setWidth(c.getXWidth() > -1 ? c.getXWidth() : this.getWidth());
				}else {
					int index = tableColService.maxIndex(name, tableName);
					try {
					c = new SysTableCol()
							.setSIndex(index)
							.setXClassName(name).setXTableName(this.tableName).setXField(this.getXField())
							.setXTitle(this.getText())
							.setXAlign(SWT.LEFT)
							.setXFormat("").setXWidth(defaultWidth())
							//.setRTypeID(1)
							.setXType(1)
							.setXWidth(100)
							.setXIsShow(true)
							;
					
						tableColService.save(c);
					}catch(Exception e) {
						System.out.println(e);
					}
					
					//this.setWidth(defaultWidth());
					this.setText(c.getXTitle() != null ? c.getXTitle() : this.getText());
					this.setWidth(c.getXWidth() > -1 ? c.getXWidth() : this.getWidth());
				}
			}
			
			// 注册监听器:改变宽度时记录下来
			this.addControlListener(new ControlAdapter() {
				@Override
				public void controlResized(ControlEvent e) {
					if(self.xField != null && self.xField.length() > 0 
							&& self.tableName != null && self.tableName.length() > 0) {
						String name = self.getParent().getShell().getClass().getName();
						// YTTableCol c = tableColService.find(name, tableName, xField);
						SysTableCol c = tableColService.find(name, tableName, xField);
						if(c != null) {
							c.setXAlign(SWT.LEFT).setXClassName(name).setXField(getXField())
							.setXFormat("").setXTitle(self.getText()).setXTableName(tableName).setXWidth(self.getWidth());
							//tableColService.update(c);
						}else {
							c = new SysTableCol().setSIndex(tableColService.maxIndex(name, tableName)).setXAlign(SWT.LEFT).setXClassName(name).setXField(getXField())
									.setXFormat("").setXTitle(self.getText()).setXTableName(tableName).setXWidth(self.getWidth())
									.setXType(1).setXIsShow(true);
							//tableColService.save(c);
						}
						tableColService.saveOrUpdate(c);
						//s(c);
						//colSetting = c;
						//s();
						/**
						colSetting = c;
						deadtime = new Timestamp(DateUtil.getCurrentTimestamp().getTime() + 1000);
						synchronized(thread) {
							if(thread == null) {
								thread = new Thread(task);
								thread.start();
							}
						}
						**/
					}
				}
			});
		}catch(Exception e) {
			this.setWidth(128);
		}
	}
	/**
	protected YTTableCol colSetting = null;
	int i = 0;
	boolean waiting = false;
	private void s() {
		if(waiting)
			return;
		else {
			this.waiting = true;
			Runnable r = new Runnable() {
				@Override
				public void run() {
					try {
						this.wait(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if(colSetting != null) {
						Timestamp before = DateUtil.getCurrentTimestamp();
						SQLite.getInstance().tablecolService.saveOrUpdate(colSetting);
						System.out.println(++i + "," + (DateUtil.getCurrentTimestamp().getTime() - before.getTime()));
					}
				}
			};
			synchronized(r) {
				r.run();
			}
			this.waiting = false;
					
		}
		
	}**/
	/**
	
	protected Timestamp deadtime = null;
	
	protected Thread thread = null;
	protected Runnable task = new Runnable(){
		@Override
		public void run() {
			synchronized("lk") {
				if(colSetting != null && deadtime != null) {
					while(DateUtil.getCurrentTimestamp().before(deadtime)) {
						try {
							this.wait(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
							Msg.error(self.getParent().getShell(), "写入配置失败");
							return;
						}
					}
					s();
					colSetting = null;
					deadtime = null;
				}
			}
		}
	};
	**/
	public int defaultWidth() {
		return defaultWidth(this.xField);
	}
	
	public static int defaultWidth(String field) {
		int rs = 128;
		if(field == null || field.endsWith("ID") || field.endsWith("ndex") || field.endsWith("sVersion") || field.endsWith("sStatus")) {
			rs = 64;
		}else if(field.endsWith("sCreateTime") || field.endsWith("sLastUpdate")) {
			rs = 160;
		}
		return rs;
	}
	
	
	public void setDefaultWidth() {
		if(self.xField != null && self.xField.length() > 0 
				&& self.tableName != null && self.tableName.length() > 0) {
			// IYTTableColService tableColService = SQLite.getInstance().tablecolService;
			ISysTableColService tableColService = Aop.get(ISysTableColService.class);
			
			String name = self.getParent().getShell().getClass().getName();
			SysTableCol c = tableColService.find(name, tableName, xField);
			if(c != null) {
				// tableColService.delete(c);
				c.setXWidth(this.defaultWidth());
				tableColService.update(c);
			}
			this.setWidth(this.defaultWidth());
		}
	}

	@Override
	protected void checkSubclass() {}
	public String getTableName() {
		return tableName;
	}
	public String getXField() {
		return xField;
	}
	/**
	public YTTableColItem getReplace(int xValue) {
		YTTableCol c = SQLite.getInstance().tablecolService.find(((WTable)self.getParent()).getShell().getClass().getName(), this.getTableName(), this.xField);
		YTTableColItem item = null;
		if(c != null) {
			item = SQLite.getInstance().tablecolItemService.findByXValue(c.getSID(), xValue);
		}
		//return c != null ? SQLite.getInstance().tablecolItemService.list(c.getSID()) : null;
		return item;
	}
	**/
	/**
	public WTableColumn setReplace(Map<String, String> replace) {
		this.replace = replace;
		return this;
	}
	**/
	/**
	public WTableColumn setTableName(String tableName) {
		this.tableName = tableName;
		return this;
	}
	**/
	public String getFormat() {
		return format;
	}
	public WTableColumn setFormat(String format) {
		this.format = format;
		return this;
	}
	public int getType() {
		return type;
	}
	public WTableColumn setType(int type) {
		this.type = type;
		return this;
	}
}
